import importlib
import pkgutil
from django.apps import apps
from common.utils.logger import Logger
from .scheduler import scheduler

def discover_tasks():
    """发现并注册所有标记的定时任务"""
    for app_config in apps.get_app_configs():
        try:
            # 尝试导入 tasks 模块
            module = importlib.import_module(f"{app_config.name}.tasks")
            
            # 查找所有标记了定时任务的函数
            for name in dir(module):
                obj = getattr(module, name)
                if hasattr(obj, '_is_scheduled') and obj._is_scheduled:
                    # 注册任务
                    schedule_args = getattr(obj, '_schedule_args', {})
                    job = scheduler.add_job(obj, **schedule_args)
                    Logger.info(f"Registered scheduled task: {name} with job ID: {job.id}")
                    
        except ImportError:
            # 如果没有 tasks 模块，跳过
            continue
        except Exception as e:
            Logger.error(f"Error discovering tasks in {app_config.name}: {str(e)}") 